<?php
/**
 * 通联支付
 * Member: rowan
 * Date: 2017/8/4 Time: 19:05
 */
namespace app\api\service;

class Allinpay
{
    private $appid;
    private $cusid;
    private $appkey;
    private $apiurl;
    private $apiversion;


    public function __construct(){
        $this->appid = config('allinpay.appid');
        $this->cusid = config('allinpay.cusid');
        $this->appkey = config('allinpay.appkey');
        $this->apiurl = config('allinpay.apiurl');
        $this->apiversion = config('allinpay.apiversion');
        $this->notify_url = config('allinpay.notify_url');
    }

    /**
    * 下单
    */
    public function pay($params){
        if(empty($params['trxamt']) || empty($params['reqsn']) || empty($params['remark']) || empty($params['acct']))return false;

        $this->apiurl .= "/pay";
        $params["sub_appid"] = 'wxc9a03270b4c9eb48';
        $params["cusid"] = $this->cusid;
        $params["appid"] = $this->appid;
        $params["version"] = $this->apiversion;
        $params["paytype"] = "W06";
        $params["randomstr"] = time();//
        $params["notify_url"] = $this->notify_url;
        $params["limit_pay"] = "no_credit";
        $params["signtype"] = "RSA";
        $params["sign"] = $this->SignArray($params);//签名
        $paramsStr = self::ToUrlParams($params,true);
		
        $rsp = $this->request($this->apiurl,$paramsStr);
		
        return json_decode($rsp, true);
    }


    /**
     * 将参数数组签名
     */
    public function SignArray(array $array)
    {
        ksort($array);
        $bufSignSrc = self::ToUrlParams($array, false);
        $private_key = "MIIEowIBAAKCAQEAw+YXIN9Ba2H5xVFQ0royoE6nNOpQo+vnBWOdLfJa6qxDetIEOoBXAhBOmwT6EoCud59MeFNCVBcnKl2BJrD6TC30876Z+UBQBXTdWd3pP6HRwJ6SK6VkXH+y7nKgjuvj/o30c4uLhNd/tBVuwAJdWdabLFm9aoSJo8Cc/Vo81Pct0tpTJLo+wAC1nKqtBO8q6+IMylJiKwE0Qm7nLdglrqs5+PbR5TdL/U6vCez0XO3OKge30pPgSAUa2KGg+ynUTtZDhpuL89LY72Wa9aJZlUVYUpBWKxNDPe+KKAl4dFW+i7BLdh0q9QCNohqHGcLXZ0kzpuaSwyvBo7Hnpbo0JwIDAQABAoIBAA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13em8c0t0CCAjxTn6Jv4jdX5IT3js7pwqbJqQCN6saPU+9IXW1mIPl3kacsp9yoGfkqajTPyggq1xd57KoyEV1cX2zR0+7u6wcVaQb2r67aOk4qY134rHJIW/CB7uATjt+";
        $private_key = chunk_split($private_key, 64, "\n");
        $key = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($private_key) . "-----END RSA PRIVATE KEY-----";
        if (openssl_sign($bufSignSrc, $signature, $key)) {
            // echo 'sign success';
        } else {
            echo 'sign fail';
        }
        //加密后的内容通常含有特殊字符，需要编码转换下，在网络间通过url传输时要注意base64编码是否是url安全的
        $sign = base64_encode($signature);
        return $sign;
    }

	public static function ToUrlParams(array $array, $encodeFlag)
    {
        $buff = "";
        foreach ($array as $k => $v) {
            if ($v != "" && !is_array($v)) {
                if ($encodeFlag) {
                    $buff .= $k . "=" . urlencode($v) . "&";
                } else {
                    $buff .= $k . "=" . $v . "&";
                }
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    //发送请求操作仅供参考,不为最佳实践
	public function request($url, $params)
	{
		header("Content-type:text/html;charset=utf-8");
		$ch = curl_init();
		$this_header = array("content-type: application/x-www-form-urlencoded;charset=UTF-8");
		curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);

		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}

    //验签
    public function validSign($array){
		if(is_array($array) && !empty($array)){
			$sign = $array['sign'];
			// echo "sign:" . $sign . "</br>";
			unset($array['sign']);
			ksort($array);
			$bufSignSrc = self::ToUrlParams($array, false);
			// var_dump($array);die;
			// echo "bufSignSrc:" . $bufSignSrc . "</br>";
			$public_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCm9OV6zH5DYH/ZnAVYHscEELdCNfNTHGuBv1nYYEY9FrOzE0/4kLl9f7Y9dkWHlc2ocDwbrFSm0Vqz0q2rJPxXUYBCQl5yW3jzuKSXif7q1yOwkFVtJXvuhf5WRy+1X5FOFoMvS7538No0RpnLzmNi3ktmiqmhpcY/1pmt20FHQQIDAQAB';
			$public_key = chunk_split($public_key, 64, "\n");
			$key = "-----BEGIN PUBLIC KEY-----\n$public_key-----END PUBLIC KEY-----";
			$result = openssl_verify($bufSignSrc, base64_decode($sign), $key);
			return $result;
		}
    }
}